package com.jn.gsondemo.module;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.components.SingletonComponent;

@Module
@InstallIn(SingletonComponent.class) // 单例级别，全局有效
public class UserModule {
    // 提供自定义日期适配器
    @Provides
    public TypeAdapter<Date> provideDateTypeAdapter() {
        return new TypeAdapter<Date>() {
            private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            @Override
            public void write(JsonWriter out, Date value) throws IOException {//obj to json
                out.value(sdf.format(value));
            }

            @Override
            public Date read(JsonReader in) throws IOException {//json to obj
                try {
                    return sdf.parse(in.nextString());
                } catch (Exception e) {
                    throw new IOException("日期解析失败", e);
                }
            }
        };
    }

    // 提供配置好的Gson单例
    @Provides
    @Singleton
    public Gson provideGson(TypeAdapter<Date> dateTypeAdapter) {
        return new GsonBuilder()
                .setPrettyPrinting() // 格式化JSON
                .serializeNulls() // 序列化null值
                .registerTypeAdapter(Date.class, dateTypeAdapter) // 注册日期适配器
                .create();
    }
}
